<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="供应商id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入供应商id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="商品名称" prop="goodName">
        <el-input v-model="queryParams.goodName" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierName">
        <!-- <el-input v-model="queryParams.supplierName" placeholder="供应商名称" clearable @keyup.enter.native="handleQuery" /> -->
        <el-select v-model="queryParams.supplierName" filterable placeholder="请选择供应商" @keyup.enter.native="handleQuery">
          <el-option v-for="item in userLists" :key="item.id" :label="item.storeName" :value="item.storeName">
          </el-option>
        </el-select>
      </el-form-item>
      <!--  <el-form-item label="零售价" prop="retailPrice">
        <el-input
          v-model="queryParams.retailPrice"
          placeholder="请输入零售价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建价格" prop="createUser">
        <el-input
          v-model="queryParams.createUser"
          placeholder="请输入创建价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="区域" prop="region">
        <el-select v-model="queryParams.region" filterable placeholder="请选择" clearable>
          <el-option v-for="item in goodAreas" :key="item.id" :label="item.cityName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="" prop="classOneId">
        <el-input
          v-model="queryParams.classOneId"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="classTwoId">
        <el-input
          v-model="queryParams.classTwoId"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <!-- <el-form-item label="二级分类" prop="classOneId">
        <el-select v-model="queryParams.classOneId" placeholder="请选择" @change="getline">
          <el-option v-for="item in goodclassifyListOne" :key="item.deptName" :label="item.deptName"
            :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类" prop="classTwoId">
        <el-select v-model="queryParams.classTwoId" clearable placeholder="请选择">
          <el-option v-for="item in goodclassifyListTwo" :key="item.deptName" :label="item.deptName"
            :value="item.id"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:good:add']"
        >新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:good:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:good:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:good:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodList" @selection-change="handleSelectionChange" height="680px" row-key="id"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="" align="center" prop="id" /> -->
      <!-- <el-table-column label="供应商id" align="center" prop="userId" /> -->
      <el-table-column label="名称" align="center" prop="goodName" />
      <el-table-column label="商品图片" align="center" prop="goodImg" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.goodImg" :width="50" :height="50" />
        </template>
      </el-table-column>

      <el-table-column label="供应商名称" align="center" prop="supplierName" />
      <el-table-column label="进货价(￥)" align="center" prop="tradePrice" />
      <el-table-column label="零售价(￥)" align="center" prop="retailPrice" />
      <el-table-column label="区域" align="center" prop="regionName" />
      <!-- <el-table-column label="累计库存数量" align="center" prop="grandCounts" /> -->
      <el-table-column label="现有库存量" align="center" prop="counts" />
      <el-table-column label="总销售量" align="center" prop="totalSellCount" />
      <!-- <el-table-column label="详情" align="center" prop="goodDetail" :show-overflow-tooltip='true' /> -->
      <!-- <el-table-column label="说明" align="center" prop="goodText" :show-overflow-tooltip='true' /> -->
      <!-- <el-table-column label="二维码url" align="center" prop="qrCodeUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.qrCodeUrl" :width="50" :height="50"/>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="审核状态" align="center" prop="status" width="100">
           <template slot-scope="scope">
              <span v-if="scope.row.status==0">待审核</span>
              <span v-if="scope.row.status==1">审核通过</span>
              <span v-if="scope.row.status==2">审核不通过</span>
          </template>
        </el-table-column> -->
      <!-- <el-table-column label="" align="center" prop="classOneId" />
      <el-table-column label="" align="center" prop="classTwoId" /> -->
      <el-table-column label="一级分类" align="center" prop="classOneName" />
      <el-table-column label="二级分类" align="center" prop="classTwoName" />
      <el-table-column label="三级分类" align="center" prop="classThreeName" />
      <!-- <el-table-column label="是否上架" align="center" prop="isInitiate" >
      <template slot-scope="scope">
              <span v-if="scope.row.isInitiate==0">已上架</span>
              <span v-if="scope.row.isInitiate==1">未上架</span>
          </template>
          </el-table-column> -->
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="库存版本号" align="center" prop="version" /> -->
      <el-table-column label="操作" align="center" width="250" fixed="right" v-if="isDisplayed">
        <template slot-scope="scope">
          <!--
          <el-button
            size="mini"
            type="text"
            @click="handleUp(scope.row)"
            v-hasPermi="['system:good:edit']"
            v-if="scope.row.isInitiate==1"
          >上架</el-button>

          <el-button
            size="mini"
            type="text"
            @click="handleDown(scope.row)"
            v-hasPermi="['system:good:edit']"
            v-if="scope.row.isInitiate==0"
          >下架</el-button> -->

          <el-button size="mini" type="text" @click="handleBuy(scope.row)">采购</el-button>

          <!-- <el-button
            size="mini"
            type="text"
            @click="handlePass(scope.row)"
            v-hasPermi="['system:good:audit']"
            v-if="scope.row.status==1||0?false:true"
          >审核通过</el-button>

          <el-button
            size="mini"
            type="text"
            @click="handleNopass(scope.row)"
            v-hasPermi="['system:good:audit']"
            v-if="scope.row.status==2?false:true"
          >审核不通过</el-button> -->


          <!-- <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:good:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:good:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改供应商商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="供应商id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入供应商id" />
        </el-form-item> -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="goodName">
              <el-input v-model="form.goodName" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品图片" prop="goodImg">
          <image-upload v-model="form.goodImg" />
        </el-form-item>
        <el-form-item label="详情">
          <editor v-model="form.goodDetail" :min-height="192" />
        </el-form-item>
        <!-- <el-form-item label="描述" prop="goodDesc">
          <el-input v-model="form.goodDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->

        <el-row>
          <el-col :span="12">
            <el-form-item label="批发价" prop="tradePrice">
              <el-input v-model="form.tradePrice" placeholder="请输入批发价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="零售价" prop="retailPrice">
              <el-input v-model="form.retailPrice" placeholder="请输入零售价" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="创建价格" prop="createUser">
          <el-input v-model="form.createUser" placeholder="请输入创建价格" />
        </el-form-item> -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="区域" prop="region">
              <el-input v-model="form.region" placeholder="请输入区域" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- <el-form-item label="累计库存数量" prop="grandCounts">
          <el-input v-model="form.grandCounts" placeholder="请输入累计库存数量" />
        </el-form-item> -->
            <el-form-item label="数量" prop="counts">
              <el-input v-model="form.counts" placeholder="请输入数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="总销售数量" prop="totalSellCount">
          <el-input v-model="form.totalSellCount" placeholder="请输入总销售数量" />
        </el-form-item> -->



        <!-- <el-form-item label="二维码url" prop="qrCodeUrl">
          <image-upload v-model="form.qrCodeUrl"/>
        </el-form-item> -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="一级分类" prop="classOneId">
              <el-select v-model="form.classOneId" placeholder="请选择" @change="getline">
                <el-option v-for="item in goodclassifyListOne" :key="item.deptName" :label="item.deptName"
                  :value="item.id"></el-option>
              </el-select>
              <!-- <el-input v-model="form.classOneId" placeholder="请输入" /> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二级分类" prop="classTwoId">
              <el-select v-model="form.classTwoId" placeholder="请选择">
                <el-option v-for="item in goodclassifyListTwo" :key="item.deptName" :label="item.deptName"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>
        <el-form-item label="说明" prop="goodText">
          <el-input v-model="form.goodText" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item> -->
        <!-- <el-form-item label="" prop="classOneName">
          <el-input v-model="form.classOneName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="" prop="classTwoName">
          <el-input v-model="form.classTwoName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item>
        <el-form-item label="库存版本号" prop="version">
          <el-input v-model="form.version" placeholder="请输入库存版本号" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="buytitle" :visible.sync="buyopen" width="500px" append-to-body>
      <el-form ref="buyform" :model="buyform" :rules="buyrules" label-width="80px">
        <el-form-item label="采购数量" prop="counts">
          <el-input v-model="buyform.counts" placeholder="请输入采购数量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="buySubmitForm">确 定</el-button>
        <el-button @click="buyCancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-button v-if="isDisplayed" type="primary" size="medium"
      style="position: fixed;bottom: 100px;right: 100px;z-index: 99 !important;" @click="toShoppingCar">我的采购<i
        class="el-icon-s-goods el-icon--right"></i></el-button>
  </div>
</template>

<script>
import { listGood, getGood, delGood, addGood, updateGood, buyGood } from "@/api/fx/suppliergood";
import { listGoodclassify } from "@/api/fx/goodclassify";
import { listArea } from "@/api/fx/goodArea";
import { suppliersList } from "@/api/fx/user";
import Cookies from "js-cookie";

export default {
  name: "index_purchase",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商商品表格数据
      goodList: [],
      goodAreas: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 采购弹出层标题
      buytitle: "",
      // 采购是否显示弹出层
      buyopen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        goodName: null,
        goodDesc: null,
        tradePrice: null,
        retailPrice: null,
        createUser: null,
        region: null,
        grandCounts: null,
        counts: null,
        totalSellCount: null,
        goodImg: null,
        goodDetail: null,
        goodText: null,
        supplierName: null,
        qrCodeUrl: null,
        status: 2,
        classOneId: null,
        classTwoId: null,
        classOneName: null,
        classTwoName: null,
        isInitiate: 0,
        version: null
      },
      // 表单参数
      form: {},
      //是否展示采购按钮
      isDisplayed: false,
      goodclassifyList: [],
      goodclassifyListOne: [],
      goodclassifyListTwo: [],
      // 表单校验
      rules: {
        goodName: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        goodDesc: [
          { required: true, message: "描述不能为空", trigger: "blur" }
        ],
        tradePrice: [
          { required: true, message: "批发价不能为空", trigger: "blur" }
        ],
        retailPrice: [
          { required: true, message: "零售价不能为空", trigger: "blur" }
        ],
        goodImg: [
          { required: true, message: "商品图片不能为空", trigger: "blur" }
        ],
        goodDetail: [
          { required: true, message: "详情图片不能为空", trigger: "blur" }
        ],
      },
      // 采购表单参数
      buyform: {},
      // 采购表单校验
      buyrules: {
        counts: [
          { required: true, message: "采购数量不能为空", trigger: "blur" }
        ],
      },
      counts: 0,
      userLists: [],
    };
  },
  created() {
    this.getList();
    this.getlistGoodclassify();
    this.getGoodlistArea();

    const roles = JSON.parse(Cookies.get("roles"));
    roles.forEach(item => {
      if (item == 'store') {
        this.isDisplayed = true
      }
    })
    this.getUserList()

  },
  methods: {
    getUserList() {
      suppliersList().then(res => {
        console.log(res, 888888888);

        if (res.code === 200)
          this.userLists = res.data
      })
    },
    //跳转采购信息
    toShoppingCar() {
      this.$router.push({
        path: '/order/goodpurc'
      })
    },

    getGoodlistArea() {
      const areaqueryParams = {
        pageNum: 1,
        pageSize: 50,
      }
      listArea(areaqueryParams).then(response => {
        this.goodAreas = response.rows;
        // console.log(this.goodAreas);
      });
    },




    getlistGoodclassify() {
      // listGoodclassify(this.queryParams).then(response => {
      //   this.goodclassifyList = response.rows;
      //   console.log( response.rows,8888888888888);
      //   this.goodclassifyListOne = this.goodclassifyList.filter(item => item.tier==1);
      // });
      let params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      }
      listGoodclassify(params).then(response => {
        this.goodclassifyList = response.rows;
        console.log(response.rows, 8888888888888);
        this.goodclassifyListOne = this.goodclassifyList.filter(item => item.tier == 1);
      });
    },
    getline(row) {
      this.goodclassifyListTwo = this.goodclassifyList.filter(item => item.parentId == parseInt(row));
      this.form.classTwoId = '';
    },
    /** 查询供应商商品列表 */
    getList() {
      this.loading = true;
      listGood(this.queryParams).then(response => {
        this.goodList = this.handleTree(response.rows, "id");
        this.total = response.total;
        this.loading = false;
      });
    },
    buyCancel() {
      this.buyopen = false;
      this.buyform = {};
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        goodName: null,
        goodDesc: null,
        tradePrice: null,
        retailPrice: null,
        createTime: null,
        createUser: null,
        remark: null,
        region: null,
        grandCounts: null,
        counts: null,
        totalSellCount: null,
        goodImg: null,
        goodDetail: null,
        goodText: null,
        qrCodeUrl: null,
        status: null,
        classOneId: null,
        classTwoId: null,
        classOneName: null,
        classTwoName: null,
        delFlag: null,
        isInitiate: null,
        version: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加供应商商品";
    },
    /** 上架按钮操作 */
    handleUp(row) {
      const goodid = row.id || this.ids;
      let obj = {
        id: goodid,
        isInitiate: 0
      }
      updateGood(obj).then(response => {
        this.$modal.msgSuccess("已上架");
        this.getList();
      });
    },
    /** 下架按钮操作 */
    handleDown(row) {
      const goodid = row.id || this.ids;
      let obj = {
        id: goodid,
        isInitiate: 1
      }
      updateGood(obj).then(response => {
        this.$modal.msgSuccess("已下架");
        this.getList();
      });
    },
    /** 采购按钮操作 */
    handleBuy(row) {
      this.counts = row.counts
      this.buyopen = true;
      this.buyform.goodIds = row.id || this.ids;
    },
    /** 审核通过操作 */
    handlePass(row) {
      const goodid = row.id || this.ids;
      let obj = {
        id: goodid,
        status: 1
      }
      updateGood(obj).then(response => {
        this.$modal.msgSuccess("审核通过");
        this.getList();
      });
    },
    /** 审核不通过操作 */
    handleNopass(row) {
      const goodid = row.id || this.ids;
      let obj = {
        id: goodid,
        status: 2
      }
      updateGood(obj).then(response => {
        this.$modal.msgSuccess("审核不通过");
        this.getList();
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGood(id).then(response => {
        this.form = response.data;
        this.goodclassifyListOne = this.goodclassifyList.filter(item => item.tier == 1);
        this.goodclassifyListTwo = this.goodclassifyList.filter(item => item.tier == 2);
        this.form.classOneId = parseInt(this.form.classOneId);
        this.form.classTwoId = parseInt(this.form.classTwoId)
        this.open = true;
        this.title = "修改供应商商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateGood(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGood(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    buySubmitForm() {
      this.$refs["buyform"].validate(valid => {
        if (valid) {
          if (this.buyform.counts > this.counts) {
            this.$message.warning('采购数量大于现有数量，请修改')
            return
          }
          this.buyform.counts = Number(this.buyform.counts)
          buyGood(this.buyform).then(response => {
            this.$modal.msgSuccess("采购数量添加成功");
            this.buyopen = false;
            this.buyform = {};
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除供应商商品编号为"' + ids + '"的数据项？').then(function () {
        return delGood(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fx/good/export', {
        ...this.queryParams
      }, `good_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
